package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;
   public   void add(ShoppingCartDTO shoppingCartDTO)
   {
       ShoppingCart shoppingCart=new ShoppingCart();
       BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);

       Long userId=BaseContext.getCurrentId();

shoppingCart.setUserId(userId);


       List<ShoppingCart> list=shoppingCartMapper.list(shoppingCart);
       if(list!=null&&list.size()>0)
       {
ShoppingCart cart=list.get(0);
cart.setNumber(cart.getNumber()+1);

shoppingCartMapper.update(cart);
       }
       else
       {
        Long dishId=     shoppingCartDTO.getDishId();

        if(dishId!=null)//本次添加到购物车的是菜品
        {
            Dish dish=dishMapper.getById(dishId);

            shoppingCart.setAmount(dish.getPrice());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setName(dish.getName());

        }
        else//本次添加到购物车的是套餐
        {
            Long SetmealId=shoppingCartDTO.getSetmealId();
            Setmeal setmeal=setmealMapper.getById(SetmealId);
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setAmount(setmeal.getPrice());
            shoppingCart.setImage(setmeal.getImage());
        }

        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
shoppingCartMapper.insert(shoppingCart);
       }




   }
   public   List<ShoppingCart> list()
   {
       Long userId=BaseContext.getCurrentId();
       ShoppingCart shoppingCart=ShoppingCart.builder().userId(userId)
               .build();
       List<ShoppingCart> list=    shoppingCartMapper.list(shoppingCart);
       return list;
   }
   public   void clean()
   {
       Long userId=BaseContext.getCurrentId();
       shoppingCartMapper.deleteByUserId(userId);



   }

}
